package cn.gx.kevin.controller;

import cn.gx.kevin.common.bootenv.SpringContextUtil;
import cn.gx.kevin.common.utils.AESUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import cn.gx.kevin.common.annotation.ApiDescript;
import cn.gx.kevin.common.annotation.ApiParams;
import cn.gx.kevin.common.annotation.ApiParamsDesc;
import cn.gx.kevin.common.ui.AjaxResult;
import cn.gx.kevin.common.user.ILoginUserContext;
import cn.gx.kevin.common.user.LoginUser;
import cn.gx.kevin.common.user.UserFunc;
import cn.gx.kevin.domain.Menu;
import cn.gx.kevin.domain.User;
import cn.gx.kevin.service.IMenuService;
import cn.gx.kevin.service.IUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/****
 * 一些共用的通用api封装
 * ******/
@ApiDescript("用户登录后的通用api，如修改密码，读取用户菜单")
@Controller
@RequestMapping(value = "/public")
public class PublicController {

	@Resource(name = "userService")
    IUserService userService;

	@Resource(name = "menuService")
	IMenuService menuService;

	ILoginUserContext loginUserCtx =null;

	@RequestMapping(value = "/page/{pageName}", method = RequestMethod.GET)
    public String page(@PathVariable("pageName") String pageName, HttpServletRequest request) throws Exception {
		if("info".equals(pageName)){
			String id = request.getParameter("id");
			User user = userService.get(id);
			JSONObject obj = new JSONObject();
			obj.put("id",user.getId());
			obj.put("userEmail",user.getUserEmail());
			obj.put("userPhone",user.getUserPhone());
			String entityJson = obj.toJSONString();
			request.setAttribute("entityJson",entityJson);
		}
		return "public/"+pageName;
    }
	  

   
    private boolean isSamePwd(String userId,String oldPwd)  throws Exception{
    	boolean isOk = true;
    	User user = userService.get(userId);
    	String pwd = DigestUtils.md5Hex(oldPwd);
		if (!pwd.equals(user.getUserPwd())) {
			isOk = false;
		}
    	return isOk;
    }
    
   
    @ApiDescript("重置密码，要求前端加密")
	@ApiParams("{userId:'',oldPwd:'',newPwd:''}")
	@ApiParamsDesc("{userId:'用户id',oldPwd:'旧密码',newPwd:'新密码'}")
    @RequestMapping(value = "/resetpwd", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResult resetpwd(HttpServletRequest request) throws Exception {
    	AjaxResult res = new AjaxResult(0,"success");
    	String userId = request.getParameter("userId");
    	String oldPwd = request.getParameter("oldPwd");
		String newPwd = request.getParameter("newPwd");
    	oldPwd =  AESUtils.decrypt(oldPwd);
    	newPwd = AESUtils.decrypt(newPwd);
    	if(isSamePwd(userId,oldPwd)) {
    		User user = new User();
    		user.setId(userId);
    		String pwd = DigestUtils.md5Hex(newPwd);
    		user.setUserPwd(pwd);
    		userService.update(user);
    	}else {
    		res.code = 1;
    		res.message = "输入的旧密码不对！";
    	}
    	return res;
    }

	@ApiDescript("用于页面定时器，防止session过期")
	@RequestMapping(value = "/testSession", method = RequestMethod.POST)
	public @ResponseBody AjaxResult test(HttpServletRequest request) throws Exception {
		AjaxResult res = new AjaxResult(0,"success");
    	return res;
	}
	/*****  {code:'0/1',message:'',data:'权限集合、菜单集合、用户信息对象'} ******/
    @ApiDescript("获取登录用户的信息包括菜单，权限集合")
	@ApiParamsDesc("{code:'0/1',message:'',data:'权限集合、菜单集合、用户信息对象'}")
    @RequestMapping(value = "/menus", method = RequestMethod.POST)
    public @ResponseBody AjaxResult menus(HttpServletRequest request) throws Exception {
        AjaxResult res = new AjaxResult(0,"success");
        if(  loginUserCtx == null){
			Object ctxObj = SpringContextUtil.getBean("loginUserContext");
			loginUserCtx = (ILoginUserContext)ctxObj;
		}
		LoginUser user = loginUserCtx.getCurrentUser();
		List<Object> listMenu = loginUserCtx.getUserMenus();
		List<Menu> menus = new ArrayList<>();
		for(Object obj : listMenu){
			menus.add((Menu)obj);
		}
		JSONArray json = menuService.getMenuJson("0", menus);
		JSONObject data = new JSONObject();
		Map<String, List<UserFunc>> authorMap = user.getAuthMap();
		data.put("authors",authorMap);
		String account = user.getAccount();
		data.put("account" , account);
		String userId = user.getId();
		data.put("userId" , userId);
		String userName = user.getUserName();
		data.put("userName" , userName);
		String orgId = user.getOrgId();
		data.put("orgId" , orgId);
		String orgName = user.getOrgName();
		data.put("orgName" , orgName);
		String sessionId = user.getSessionId();
		data.put("sessionId" , sessionId);
		boolean isSuperAdmin = user.isSuperAdmin();
		data.put("isSuperAdmin" , isSuperAdmin);
		data.put("menus" , json);
		res.data = data;
        return res;
    }

	@ApiDescript("修改个人信息")
	@RequestMapping(value = "/updateinfo", method = RequestMethod.POST)
	public @ResponseBody
	AjaxResult updateInfo(HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult(0,"");
		String oldPwd = request.getParameter("oldPwd");
		String userPwd = request.getParameter("userPwd");
		String userPhone = request.getParameter("userPhone");
		String userEmail = request.getParameter("userEmail");
		String id = request.getParameter("id");
		if(StringUtils.isNotEmpty(userPwd)){
			String _pwd = DigestUtils.md5Hex(oldPwd);
			User u = this.userService.get(id);
			if(!u.getUserPwd().equals(_pwd)){
				result.code = 1;
				result.message = "旧密码不正确！";
				return result;
			}
		}
		User bean = new User();
		bean.setId(id);
		if(StringUtils.isNotEmpty(userPwd)){
			String _pwd = DigestUtils.md5Hex(userPwd);
			bean.setUserPwd(_pwd);
		}
		bean.setUserPhone(userPhone);
		bean.setUserEmail(userEmail);
		this.userService.update(bean);
		return result;
	}

}
